package com.siki.salessystemoauth2server.util.phoneverification;

import java.util.Random;

/**
 * @author keyvonchen
 * @Date 2021/6/8
 */
public class VerificationCodeUtil {
    /**
     * 默认字符集
     */
    public static final String VERIFY_CODE = "1234567890";

    /**
     * 默认字符集生成验证码
     * @param verifySize 验证码长度
     * @return
     */
    public static String createVerifyCode(int verifySize) {
        return create(verifySize, VERIFY_CODE);
    }

    /**
     * 指定字符集生成验证码
     * @param verifySize 验证码长度
     * @param sources 字符集
     * @return
     */
    public static String createVerifyCode(int verifySize, String sources) {
        return create(verifySize, sources);
    }

    private static String create(int verifySize, String sources) {
        if (sources == null || sources.length() == 0) {
            sources = VERIFY_CODE;
        }
        int codeLen = sources.length();
        Random r = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(r.nextInt(codeLen - 1)));
        }
        return verifyCode.toString();
    }

    public static String createSmsCacheKey(String prefix, String phone, String businessStr) {
        return prefix + "_" + businessStr + "_" + phone;
    }

    // test
    public static void main(String[] args) {
        System.out.println(createVerifyCode(6));
    }
}
